package com.example.hqpatrol.fragment;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.hqpatrol.R;
import com.example.hqpatrol.base.BaseFragment;
import com.example.hqpatrol.broad.MyBroadcastReceiver;
import com.example.hqpatrol.common.util.GsonUtil;
import com.example.hqpatrol.databinding.FragmentPatrolInputBinding;
import com.example.hqpatrol.entity.item.PatrolUserSelectItem;
import com.example.hqpatrol.entity.patrol.PatrolDetail;
import com.example.hqpatrol.entity.patrol.PatrolFeedback;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.reflect.TypeToken;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.SnackbarUtils;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.actionbar.TitleUtils;
import com.xuexiang.xui.widget.button.RippleView;
import com.xuexiang.xui.widget.dialog.DialogLoader;
import com.xuexiang.xui.widget.grouplist.XUICommonListItemView;
import com.xuexiang.xui.widget.grouplist.XUIGroupListView;
import com.xuexiang.xui.widget.layout.XUILinearLayout;
import com.xuexiang.xui.widget.spinner.materialspinner.MaterialSpinner;
import com.xuexiang.xui.widget.statelayout.StatefulLayout;
import com.xuexiang.xutil.app.FragmentUtils;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.util.StrUtil;

@Page
public class PatrolInputFragment extends BaseFragment<FragmentPatrolInputBinding> {

    public static final String BUNDLE_KEY_ID = "id";
    public static final String BUNDLE_KEY_TITLE = "title";
    public static final String BUNDLE_KEY_POSITION = "position";
    private Long id;

    //状态图标填充
    private StatefulLayout patrol_full_state_layout;
    private XUIGroupListView xuiGroupListView;

    //当前巡检实体模型
    private PatrolDetail patrolDetailModel;
    //当前巡检反馈列表内容
    private List<PatrolFeedback> patrolFeedbackList;
    //当前巡检的选择巡检人列表
    private List<PatrolUserSelectItem> patrolUserSelectItemList;
    //广播
    private MyBroadcastReceiver broadcastReceiver;

    @NonNull
    @Override
    protected FragmentPatrolInputBinding viewBindingInflate(LayoutInflater inflater, ViewGroup container) {
        return FragmentPatrolInputBinding.inflate(inflater, container, false);
    }

    @Override
    protected TitleBar initTitle() {
        Bundle bundle = getArguments();
        if(bundle != null) {
            TitleBar titleBar = TitleUtils.addTitleBarDynamic((ViewGroup) getRootView(), bundle.getString(BUNDLE_KEY_TITLE), v -> popToBack());
            titleBar.setBackgroundColor(ResUtils.getColor(getContext(), R.color.colorPrimary));
            return titleBar;
        }else{
            return TitleUtils.addTitleBarDynamic((ViewGroup) getRootView(), "未知任务", v -> popToBack());
        }
    }

    @Override
    protected void initViews() {
        component();
        Bundle bundle = getArguments();
        if(bundle != null){
            id = bundle.getLong(BUNDLE_KEY_ID);
            patrol_full_state_layout.showLoading();
            XHttp.get("https://www.shhanqian.com:18022/core/patrol/get/" + id).execute(new SimpleCallBack<PatrolDetail>() {

                @Override
                public void onSuccess(PatrolDetail patrolDetail) throws Throwable {
                    patrol_full_state_layout.showContent();
                    patrolDetailModel = patrolDetail;

                    XUIGroupListView.Section section = XUIGroupListView.newSection(getContext());
                    View.OnClickListener onClickListener = v -> {
                        if (v instanceof XUICommonListItemView) {
                            CharSequence text = ((XUICommonListItemView) v).getText();
                            XToastUtils.toast(text + " is Clicked");
                        }
                    };

                    XUICommonListItemView patrolTypeView = xuiGroupListView.createItemView("巡检类型");
                    patrolTypeView.setOrientation(XUICommonListItemView.VERTICAL);
                    patrolTypeView.setDetailText(patrolDetailModel.getPatrolType());
                    section.addItemView(patrolTypeView, onClickListener);

                    XUICommonListItemView unitNameView = xuiGroupListView.createItemView("单位名称");
                    unitNameView.setOrientation(XUICommonListItemView.VERTICAL);
                    unitNameView.setDetailText(patrolDetailModel.getUnitName());
                    section.addItemView(unitNameView, onClickListener);

                    XUICommonListItemView patrolObjectView = xuiGroupListView.createItemView("巡检对象");
                    patrolObjectView.setOrientation(XUICommonListItemView.VERTICAL);
                    patrolObjectView.setDetailText(patrolDetailModel.getPatrolObject());
                    section.addItemView(patrolObjectView, onClickListener);

                    XUICommonListItemView planPatrolTopicView = xuiGroupListView.createItemView("巡检计划主题");
                    planPatrolTopicView.setOrientation(XUICommonListItemView.VERTICAL);
                    planPatrolTopicView.setDetailText(patrolDetailModel.getPlanPatrolTopic());
                    section.addItemView(planPatrolTopicView, onClickListener);

                    XUICommonListItemView requireTimeView = xuiGroupListView.createItemView("要求巡检时间");
                    requireTimeView.setOrientation(XUICommonListItemView.VERTICAL);
                    requireTimeView.setDetailText(patrolDetailModel.getRequireTime());
                    section.addItemView(requireTimeView, onClickListener);

                    if(patrolDetailModel.getStep() == 1 || patrolDetailModel.getStep() == 2){
                        XUICommonListItemView userNameView = xuiGroupListView.createItemView("巡检人员");
                        userNameView.setOrientation(XUICommonListItemView.VERTICAL);
                        userNameView.setDetailText(patrolDetailModel.getPatrolUserName());
                        section.addItemView(userNameView, onClickListener);
                    }else{
                        XUICommonListItemView userNameView = xuiGroupListView.createItemView("巡检人员");
                        userNameView.setOrientation(XUICommonListItemView.VERTICAL);
                        userNameView.setDetailText(patrolDetailModel.getUserName());
                        section.addItemView(userNameView, onClickListener);
                    }

                    if(patrolDetailModel.getStep() == 0){
                        XUICommonListItemView userNameSelectView = xuiGroupListView.createItemView("本次巡检人员");
                        userNameSelectView.setAccessoryType(XUICommonListItemView.ACCESSORY_TYPE_CUSTOM);

                        XUILinearLayout xuiLinearLayout = new XUILinearLayout(getContext());
                        xuiLinearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                        xuiLinearLayout.setBorderWidth(2);
                        xuiLinearLayout.setBorderColor(ResUtils.getColor(getContext(), R.color.colorPrimary));

                        MaterialSpinner materialSpinner = new MaterialSpinner(getContext());
                        patrolUserSelectItemList = PatrolUserSelectItem.getList(patrolDetail);
                        materialSpinner.setItems(patrolUserSelectItemList);
                        materialSpinner.setOnItemSelectedListener((spinner, position, id, item) -> {
                            PatrolUserSelectItem user = patrolUserSelectItemList.get(position);
                            if(StrUtil.isNotBlank(user.getId())){
                                patrolDetailModel.setPatrolUserId(user.getId());
                                patrolDetailModel.setPatrolUserName(user.getName());
                            }
                        });

                        xuiLinearLayout.addView(materialSpinner);
                        userNameSelectView.addAccessoryCustomView(xuiLinearLayout);
                        section.addItemView(userNameSelectView, onClickListener);
                    }

                    XUICommonListItemView ifRepairSelfView = xuiGroupListView.createItemView("是否自行维修");
                    ifRepairSelfView.setAccessoryType(XUICommonListItemView.ACCESSORY_TYPE_SWITCH);
                    ifRepairSelfView.getSwitch().setChecked(patrolDetailModel.isIfRepairSelf());
                    ifRepairSelfView.getSwitch().setOnCheckedChangeListener((buttonView, isChecked) -> {
                        patrolDetailModel.setIfRepairSelf(isChecked);
                    });
                    if(!patrolDetailModel.isIfRepair()){
                        ifRepairSelfView.setVisibility(View.GONE);
                    }

                    XUICommonListItemView ifRepairView = xuiGroupListView.createItemView("是否维修");
                    ifRepairView.setAccessoryType(XUICommonListItemView.ACCESSORY_TYPE_SWITCH);
                    ifRepairView.getSwitch().setChecked(patrolDetailModel.isIfRepair());
                    ifRepairView.getSwitch().setOnCheckedChangeListener((buttonView, isChecked) -> {
                        patrolDetailModel.setIfRepair(isChecked);
                        if(isChecked){
                            ifRepairSelfView.setVisibility(View.VISIBLE);
                            patrolDetailModel.setIfRepairSelf(true);
                        }else{
                            ifRepairSelfView.setVisibility(View.GONE);
                            patrolDetailModel.setIfRepairSelf(false);
                            ifRepairSelfView.getSwitch().setChecked(false);
                        }
                    });
                    section.addItemView(ifRepairView, onClickListener);
                    section.addItemView(ifRepairSelfView, onClickListener);

                    section.setTitle("基础信息").addTo(xuiGroupListView);

                    // 巡检反馈列表，使用批量增加fragment的方式
                    patrolFeedbackList = GsonUtil.getInstance().fromJson(patrolDetail.getPatrolFeedbackJson(), new TypeToken<List<PatrolFeedback>>(){}.getType());
                    patrolFeedbackList.forEach(patrolFeedback -> {
                        FeedbackFragment feedbackFragment = new FeedbackFragment(patrolFeedback, patrolDetail);
                        FragmentUtils.add(getChildFragmentManager(), feedbackFragment, R.id.patrol_input_feedback_view);
                    });

                    //提交
                    RippleView RippleView = findViewById(R.id.patrol_input_result_btn);
                    RippleView.setOnClickListener(v -> {
                        List<PatrolFeedback> patrolFeedbackResultList = new ArrayList<>();
                        FragmentUtils.getFragments(getChildFragmentManager()).forEach(feedbackFragment -> {
                            FeedbackFragment fragment = (FeedbackFragment) feedbackFragment;
                            PatrolFeedback patrolFeedback = fragment.getFeedbackResult();
                            patrolFeedbackResultList.add(patrolFeedback);
                        });

                        String patrolFeedbackResultListJson = GsonUtil.getInstance().toJson(patrolFeedbackResultList);
                        patrolDetail.setPatrolFeedbackJson(patrolFeedbackResultListJson);
                        DialogLoader.getInstance().showConfirmDialog(getContext(), "结果", GsonUtil.getInstance().toJson(patrolDetail), "模拟完成", (dialogInterface, i) -> {
                            dialogInterface.dismiss();

                            //发送本地广播 通知列表删除此项
                            LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getContext());
                            MyBroadcastReceiver broadcastReceiver = new MyBroadcastReceiver();
                            IntentFilter intentFilter = new IntentFilter();
                            intentFilter.addAction("com.example.hqpatrol");
                            localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);
                            Intent intent = new Intent("com.example.hqpatrol");
                            bundle.putString("type", MyBroadcastReceiver.PATROL_LIST_REMOVE);
                            bundle.putBoolean("isFinished", true);
                            intent.putExtras(bundle);
                            localBroadcastManager.sendBroadcast(intent); // 发送本地广播

                            popToBack();
                        }, "关闭", (dialogInterface, i) -> {
                            dialogInterface.dismiss();
                        });
                    });
                }

                @Override
                public void onError(ApiException e) {
                    e.printStackTrace();
                    patrol_full_state_layout.showError(v -> initViews());
                    SnackbarUtils.Short(getView(), "调用远程接口失败").danger().show();
                }
            });
        }


    }

    private void component() {
        patrol_full_state_layout = findViewById(R.id.patrol_full_state_layout);
        xuiGroupListView = findViewById(R.id.patrol_input_group);
    }
}